import { Modal, Button, Form, Select, DatePicker, Cascader, Drawer, Input } from 'antd';
import type { CascaderProps } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { skillTypeList, getCoreRegion } from '@/api/user';
import moment from 'moment'; //引入富文本编辑器
import BraftEditor from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import './index.scss';
interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
}
// const FilterModal = (props: { open: boolean; onCancel: any }) => {
const FilterModal = (props: any) => {
    const { open, onCancel, onConfirm } = props;
    const [filterForm] = Form.useForm();
    const { RangePicker } = DatePicker;
    const onFinish = (values: any) => {
        console.log(values, 9);
        //
    };
    const [skillList, setSkillList] = useState<
        {
            eqSkillTypeDesc: string;
            eqSkillTypeId: string;
            eqSkillTypeName: string;
            value: string;
            label: string;
        }[]
    >([]);
    const [currentRegion, setCurrentRegion] = useState<Option[]>([]);
    const [selectRegionList, setSelectRegionList] = useState<string[]>([]);
    useEffect(() => {
        getSkill();
        fetchFirstLevelOptions();
        // getRegion('');
    }, []);
    const closeModal = () => {
        filterForm.resetFields();
        onConfirm({});
    };
    const filterOver = () => {
        const obj = filterForm.getFieldsValue();
        const { creatioTime } = obj;
        const startTime =
            creatioTime && creatioTime.length > 0
                ? dayjs(creatioTime[0]).startOf('date').format('YYYY-MM-DDTHH:mm:ss')
                : '';
        const endTime =
            creatioTime && creatioTime.length > 0
                ? dayjs(creatioTime[1]).endOf('date').format('YYYY-MM-DDTHH:mm:ss')
                : '';
        obj.sTime = startTime;
        obj.eTime = endTime;
        const currentProvinceCode = selectRegionList.length > 0 ? selectRegionList[0] : '';
        const currentCityCode = selectRegionList.length > 1 ? selectRegionList[1] : '';
        const currentDistrictCode = selectRegionList.length > 2 ? selectRegionList[2] : '';
        obj.currentProvinceCode = currentProvinceCode;
        obj.currentCityCode = currentCityCode;
        obj.currentDistrictCode = currentDistrictCode;
        const obj1 = JSON.parse(JSON.stringify(obj));

        onConfirm(obj1);
    };
    //富文本组件内容
    const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState('<p></p>'));
    //富文本输出的HTML
    const [outputHTML, setOutputHTML] = useState<any>('<p></p>');

    /**
     * @Author: YuKi
     * @description: 处理富文本框显示数据
     * @param {Object} editorState 富文本框内容
     * @return {*}
     */
    const handleEditorState = editorState => {
        setEditorState(editorState); //必须要有这一步
        setOutputHTML(editorState.toHTML()); //获取富文本框里面的内容
    };
    const getSkill = () => {
        const params = {};
        skillTypeList(params).then((res: any) => {
            console.log(res, 990);
            res.length > 0 &&
                res.map((item: any) => {
                    item.value = item.eqSkillTypeId;
                    item.label = item.eqSkillTypeName;
                });
            setSkillList(res);
        });
    };
    const formItems = [
        {
            type: 'input',
            label: 'Article title',
            key: 'ArticleTitle',
            options: [],
            placeholder: 'Enter the article title',
        },
        {
            type: 'select',
            label: 'Relationship skills',
            key: 'professionId',
            options: skillList,
            placeholder: 'Enter the relationship skill',
        },
    ];
    const disabledDate: RangePickerProps['disabledDate'] = current => {
        return current && current > dayjs().endOf('day');
    };

    const dateOnChange = date => {
        console.log(date);
    };
    const [cascaderOptions, setOptions] = useState<Option[]>([]);
    const fetchFirstLevelOptions = async () => {
        try {
            const params = {
                parentCode: '',
            };
            const response: any = await getCoreRegion(params);
            const list = response.map((item: any) => ({
                value: item.code,
                label: item.value,
                isLeaf: false, //  设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标 ，设为true，就是不展示有子节点的图标
            }));
            setOptions(list);
        } catch (error) {
            console.error('Failed to fetch first level options', error);
        }
    };

    const loadData = async (selectedOptions: Option[]) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        try {
            const params = {
                parentCode: targetOption.value || '',
            };
            const response: any = await getCoreRegion(params);
            const list = response.map((item: any) => ({
                value: item.code,
                label: item.value,
                isLeaf: false,
            }));
            setOptions(list);
            targetOption.children = list;
            setOptions([...cascaderOptions]);
        } catch (error) {
            console.error('Failed to fetch next level options', error);
            setOptions([...cascaderOptions]);
        }
    };

    const onChange = (value, selectedOptions) => {
        console.log(value, selectedOptions);
        setSelectRegionList(value);
    };
    const [controlsList, setControlsList] = useState<any[]>([
        // 'undo',
        // 'redo',
        // 'separator',
        {
            key: 'font-size', // 使用key来指定控件类型
            title: '16', // 自定义控件title
            // text: '点我选择字号', // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
        },
        // 'line-height',
        // 'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        // 'separator',
        // 'text-indent',
        'text-align',
        'separator',
        {
            key: 'headings', // 使用key来指定控件类型
            title: 'h1', // 自定义控件title
            // text: '点我选择字号', // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
        },
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'link',
        'separator',
        'hr',
        'separator',
        'media',
        'separator',
        'clear',
    ]);
    console.log(controlsList);

    //   从这里结束 级联选择器
    return (
        <Drawer
            width={580}
            maskClosable={false}
            placement="right"
            open={open}
            closable={false}
            className="deawerBox"
            // onClose={closeModal}
        >
            <div className="deawerTopBox flex-between">
                <div> Add article</div>
                <div>
                    <img src={require('@/assets/images/close-modal.png')} onClick={closeModal} alt="" />
                </div>
            </div>
            <Form
                name="filter-form"
                className="filter-form"
                form={filterForm}
                layout="vertical"
                onFinish={onFinish}
                validateTrigger="onBlur"
                autoComplete="off"
            >
                <div>
                    {formItems.map(i => {
                        return (
                            <Form.Item label={i.label} name={i.key} key={i.key}>
                                {i.type === 'select' ? (
                                    <Select
                                        className="form-select selectBox"
                                        suffixIcon={
                                            <img
                                                src={require('@/assets/images/arrowDown.png')}
                                                style={{ width: 20, height: 20 }}
                                            />
                                        }
                                        placeholder={i.placeholder}
                                    >
                                        {i.options.map(o => {
                                            return (
                                                <Select.Option value={o.value} key={o.value}>
                                                    {o.label}
                                                </Select.Option>
                                            );
                                        })}
                                    </Select>
                                ) : (
                                    <Input placeholder={i.placeholder} />
                                )}
                            </Form.Item>
                        );
                    })}

                    <Form.Item label="Article details" name="Article details">
                        <BraftEditor
                            className="my-editor"
                            value={editorState}
                            onChange={handleEditorState}
                            controls={controlsList}
                            contentStyle={{
                                height: 210,
                                boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)',
                                border: '1px solid black',
                            }}
                        />
                    </Form.Item>
                </div>
            </Form>
            <div className="drawerFooterBox flex-end">
                <Button onClick={closeModal}>Cancel</Button>
                <Button type="primary" onClick={filterOver}>
                    {' '}
                    Save{' '}
                </Button>
            </div>
        </Drawer>
    );
};
export default FilterModal;
